<template>
  <div class="largeScreen">
    <div class="headerBox">
      <div class="frc pt30 pr20">
        <div class="flc tabsBox">
          <div class="tabsItemBg cur f14 fcc flex-1" :class="tabIdx == idx ? 'selectTabsItemBg' : ''" v-for="(item, idx) in tablist" @click="tabsFun(idx)">
            <div>{{ item.name }}</div>
            <div class="down_line"></div>
          </div>
        </div>
        <div class="fcc">
          <div class="flc ml20">
            <div class="cblue">{{ currentDate }}</div>
            <div class="cwhite ml20">{{ currentTime }}</div>
            <div class="cblue"></div>
          </div>
        </div>
      </div>
        <!-- 添加光束元素 -->
      <div class="light-beam"></div>
    </div>

    <div class="fcbc chartBox p20">
      <div class="fcbc fv h1 flex-1 m-l-bg">
        <div class="mon-title f16 pl50 pt10 hand" @click="rightListC()">摄像头列表</div>
        <div class="flt flex-1 w1 pt20 pl20" style="height:100%;overflow:auto;">
          <el-tree class="w1" :data="treeData" :props="defaultProps" @node-click="handleNodeClick" node-key="id"></el-tree>
        </div>
      </div>
      <div class="fcbc fv h1 flex-4 m-r-bg">
        <div class="videoBox w1 h1 flt fw" style="overflow:auto;">
          <div class="flt flex-1 flex4 p10" v-for="(camera, idx) in cameraList" :key="camera.id">
            <div class="cameraItemBor w1 h1">
              <div class="cameraItemBox flex-1 h1">
                <div class="fcbc w1 cameraTitle">
                  <div class="cwhite">{{ camera.deviceName }}</div>
                  <div class="cur" @click="fullScreenFun(camera)">
                    <el-image
                      style="width: 20px; height: 20px"
                      :src="require(`@/assets/images/icon/fullScreen.png`)"
                      fit="fill"
                    ></el-image>
                  </div>
                </div>
                <!-- 条件判断：当 device.pic 存在且不为空时显示接口返回的图片，否则显示默认图片 -->
                <el-image 
                  v-if="camera.pic && camera.pic.trim() !== ''"
                  :src="camera.pic"
                  fit="fill" style="height: calc(100% - 59px);width: 100%;">
                </el-image>
                <el-image 
                  v-else
                  :src="require(`@/assets/images/windPower/cameraImg.png`)"
                  fit="fill" style="height: calc(100% - 59px);width: 100%;">
                </el-image>
                <!-- 添加时间显示 -->
                <div class="camera-time">{{ camera.updatedAt }}</div>
              </div>
            </div>
          </div>
          <transition name="el-zoom-in-center">
            <div v-show="zoomInCenter" class="fullScreenBox fcc w1 h1">
              <div class="flex-1" style="height: calc(100% - 110px); position: absolute; bottom: 35px; width: 100%;">
                <div class="fcbc w1 videoTitle">
                  <div class="cwhite">{{ currentCamera.name }}</div>
                  <div class="cur" @click="lessenFun">
                    <el-image style="width: 20px; height: 20px" :src="require(`@/assets/images/icon/videoBack.png`)" fit="fill"></el-image>
                  </div>
                </div>
                <div class="flex-1 w1 previewBox video-container" style="height: 100%;">
                  <video
                    ref="videoPlayer"
                    width="100%"
                    height="100%"
                    style="max-height: 880px;background-color: #000000;"
                    controls
                    autoplay
                    @loadstart="isLoading = true"
                    @canplay="isLoading = false"
                    @error="handleVideoError"
                  >
                    <source :src="currentCamera.url" type="video/mp4" />
                    您的浏览器不支持 HTML5 video 标签。
                  </video>
                    <!-- 自定义加载提示 -->
                  <div v-if="isLoading" class="loading-overlay">
                    <div class="loading-text">视频加载中...</div>
                  </div>

                  <!-- 错误提示 -->
                  <div v-if="loadError" class="error-overlay">
                    <div class="error-text">视频加载失败</div>
                  </div>
                </div>
              </div>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getLeft,rightList,rightListDj} from "@/api/dp/jkdp"
// 引入flv.min.js
import flvjs from 'flv.js';
export default {
  name: "monitoring",
  data() {
    return {
      // 点击显示的封面图和视频
      currentCamera: {
        name: "",
        url: "",
      },
      // 右侧数据
      cameraList: [
        { id: 1, deviceName: '摄像头#1', time: "2023-11-03 14:52:12",rtspUrl:'https://www.runoob.com/try/demo_source/movie.mp4' },
        { id: 2, deviceName: '摄像头#2', time: "2023-11-03 14:52:12",rtspUrl:'https://www.runoob.com/try/demo_source/movie.mp4' },
        { id: 3, deviceName: '摄像头#12', time: "2023-11-03 14:52:12",rtspUrl:'https://www.runoob.com/try/demo_source/movie.mp4' },
        { id: 4, deviceName: '摄像头#12', time: "2023-11-03 14:52:12",rtspUrl:'https://www.runoob.com/try/demo_source/movie.mp4' },
        { id: 5, deviceName: '摄像头#12', time: "2023-11-03 14:52:12",rtspUrl:'https://www.runoob.com/try/demo_source/movie.mp4' },
        { id: 6, deviceName: '摄像头#12', time: "2023-11-03 14:52:12",rtspUrl:'https://www.runoob.com/try/demo_source/movie.mp4' },
        { id: 7, deviceName: '摄像头#12', time: "2023-11-03 14:52:12",rtspUrl:'https://www.runoob.com/try/demo_source/movie.mp4' },
        { id: 8, deviceName: '摄像头#12', time: "2023-11-03 14:52:12",rtspUrl:'https://www.runoob.com/try/demo_source/movie.mp4' }
      ],
      currentDate: "",
      currentTime: "",
      zoomInCenter: false,
      isLoading: false,
      loadError: false,
      tabIdx: 1,
      tablist: [
        {
          name: "全景监视",
          path: "/operation",
        },
        {
          name: "监控大屏",
          path: "/monitoring",
        },
        {
          name: "驾驶舱总览",
          path: "/cockpit",
        },
        {
          name: "数据监测",
          path: "/detection",
        },
        {
          name: "智能分析",
          path: "/analysis",
        },
      ],
      // 监控
      flvPlayer: null,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  methods: {
    leftTree(){
      getLeft().then(response => {
        this.treeData = response.data
      })
    },
    rightListC(id){
      rightList(id).then(response => {
        this.cameraList = response.rows
      })
    },
    // 年月日时分秒
    updateDateTime() {
      const now = new Date();

      // 格式化日期（YYYY-MM-DD 星期X）
      const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const weekday = weekdays[now.getDay()];
      this.currentDate = `${year}-${month}-${day} ${weekday}`;
      // 格式化时间（HH:MM:SS）
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      this.currentTime = `${hours}:${minutes}:${seconds}`;
    },
    tabsFun(i) {
      this.tabIdx = i;
      this.$router.push(this.tablist[i].path);
    },
    handleVideoError() {
      this.isLoading = false;
      this.loadError = true;
    },
    handleNodeClick(data) {
      var that=this
      // this.videoUrl = data.videoUrl
      rightListDj(data.id,data.code).then(response => {
        that.cameraList=response.data
      })
    },
    fullScreenFun(camera) {
      // 先关闭之前的播放器（如果存在）
      this.destroyFlvPlayer();
      this.currentCamera = {
        name: camera.deviceName,
        url: camera.rtspUrl
      };
      this.zoomInCenter = true;

      // 点击监控
    // 使用 nextTick 确保 DOM 更新完成
    this.$nextTick(() => {
        if (flvjs.isSupported()) {
          const videoElement = this.$refs.videoPlayer;
          
          // 创建 FLV 播放器
          this.flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: this.currentCamera.url,
            isLive: true
          });
          
          // 附加到 video 元素
          this.flvPlayer.attachMediaElement(videoElement);
          
          // 加载并播放
          this.flvPlayer.load();
          this.flvPlayer.play().catch(e => {
            console.error('播放失败:', e);
          });
          
          // 监听错误事件
          this.flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) => {
            console.error('FLV 播放错误:', errType, errDetail);
          });
        } else {
          this.$message.error('浏览器不支持 FLV 播放');
        }
      });
    },
      // 关闭全屏时销毁播放器
    lessenFun() {
      this.destroyFlvPlayer();
      this.zoomInCenter = false;
    },
    
    // 销毁 FLV 播放器
    destroyFlvPlayer() {
      if (this.flvPlayer) {
        try {
          // 暂停播放
          this.flvPlayer.pause();
          // 卸载资源
          this.flvPlayer.unload();
          // 分离媒体元素
          this.flvPlayer.detachMediaElement();
          // 销毁播放器（这会关闭 WebSocket 连接）
          this.flvPlayer.destroy();
        } catch (e) {
          console.error('销毁播放器时出错:', e);
        } finally {
          this.flvPlayer = null;
        }
      }
    },
    
    beforeDestroy() {
      // 组件销毁时也清理播放器
      this.destroyFlvPlayer();
      clearInterval(this.timer);
    },

      // 增强版数据刷新方法
    async refreshData() {
      try {
        await Promise.all([
          this.leftTree(),
          this.rightListC('')
        ]);
        console.log('数据刷新成功', new Date().toLocaleString());
      } catch (error) {
        console.error('数据刷新失败:', error);
      }
    },
    
    // 初始化定时器
    initRefreshTimer() {
      // 先清除旧定时器
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
      }
      
      // 设置定时器 (1分钟)
      this.refreshInterval = setInterval(() => {
        this.refreshData();
      }, 60000);
    }
  },
  mounted() {
    // 初始化定时刷新
    this.initRefreshTimer();

    this.leftTree()
    this.rightListC("")
    // 初始更新
    this.updateDateTime();

    // 每秒更新一次
    this.timer = setInterval(this.updateDateTime, 1000);
  },
  beforeDestroy() {
    // 清除定时器，防止内存泄漏
    clearInterval(this.timer);
  }
};
</script>

<style scoped lang="scss">
.largeScreen {
  width: 100%;
  height: 100%;
  background-color: #000f21;
  position: relative;
}
.headerBox {
  background-image: url("~@/assets/images/windPower/titleMax.png");
  background-size: 100% 100%;
  height: 84px;
  min-height: 84px;
  max-height: 84px;
  width: 100%;
  position: relative;
  z-index: 99;
  overflow: hidden; /* 确保光束不会溢出 */
  /* 光束元素样式 */
.light-beam {
  position: absolute;
  top: 0;
  left: -80%; /* 初始位置在左侧外部 */
  width: 100px;
  height: 3px;
  background: linear-gradient(to left, 
              #ffffff, 
              rgba(255,255,255,0.8),
              rgba(255,255,255,0.5),
              rgba(255,255,255,0.2),
              transparent);

  transform: skewX(-20deg); /* 使光束倾斜 */
  animation: beam-scan 5s linear infinite;
  z-index: 1;
}

/* 光束动画 */
@keyframes beam-scan {
  0% {
    left: -50%;
    opacity: 0;
    top: 63px;
  }
  20% {
    opacity: 0.8;
    top: 63px;
  }
  40% {
    opacity: 0.8;
    top: 63px;
  }
  43% {
    opacity: 0;
    top: 63px;

  }
  46% {
    opacity: 0;
    top: 63px;

  }
  47% {
    opacity: 0.8;
    top: 15px;
  }
  80% {
    opacity: 0.8;
    top: 15px;
  }
  90% {
    opacity: 0.8;
    top: 15px;
  }
  100% {
    left: 100%;
    opacity: 0;
    top: 15px;
  }
}

/* 确保标题内容在光束之上 */
.headerBox > * {
  position: relative;
  z-index: 2;
}
  .tabsBox {
    width: 45%;
    .tabsItemBg {
      background-image: url("~@/assets/images/windPower/tabs.png");
      background-size: 100% 100%;
      height: 40px;
      color: #45a2ff;
      position: relative;
      .down_line {
        display: none;
        position: absolute;
        background-image: url("~@/assets/images/windPower/select-tabs.png");
        background-size: 100% 100%;
        width: 80%;
        height: 33px;
        top: 22px;
      }
    }
    .tabsItemBg:hover {
      color: #ffffff;
      .down_line {
        display: block;
      }
    }
    .selectTabsItemBg {
      color: #ffffff;
      .down_line {
        display: block;
      }
    }
  }
}
.cblue {
  color: #45a2ff;
}
.cwhite {
  color: #ffffff;
}
.cgray {
  color: #999999;
}
.hand{
  cursor: pointer;
}
.chartBox {
  height: calc(100% - 84px);
  position: relative;
  z-index: 1;
  .chartTile {
    color: #ffffff;
    background-image: url("~@/assets/images/windPower/titleMin.png");
    background-size: 100% 100%;
    height: 40px;
    width: 100%;
    font-weight: bold;
  }
  .icon-electricity {
    color: #0aa7ff;
    background-image: url("~@/assets/images/icon/icon-electricity.png");
    background-size: 100% 100%;
    height: 50px;
    width: 50px;
  }
}
.mon-title {
  background: url("~@/assets/images/windPower/m-title.png");
  background-size: 100% 100%;
  width: 100%;
  height: 40px;
  color: #ffffff;
}
.m-l-bg {
  background: url("~@/assets/images/windPower/m-l-bg.png");
  background-size: 100% 100%;
}
.m-r-bg {
  background: url("~@/assets/images/windPower/m-bg.png");
  background-size: 100% 100%;
}
.videoBox {
  align-items: baseline;
  justify-content: flex-start;
  position: relative;
  margin: 35px 0;
    padding: 0 20px;
  .videoTitle {
    padding: 5px 10px;
    background-color: #1b7ef280;
  }
  .cameraItemBor {
    background: url("~@/assets/images/windPower/cameraBor.png");
    background-size: 100% 100%;
    padding: 10px;
    height: 100%;
  }
  .cameraItemBox {
    // background: url("~@/assets/images/windPower/cameraImg.png");
    background-size: 100% 100%;
    height: 100%;
  }
  .cameraTitle {
    background: url("~@/assets/images/windPower/cameraTitle.png");
    background-size: 100% 100%;
    padding: 5px 10px;
  }
  .flex4 {
    flex: 0 0 25%;
    height: calc(100% / 3);
  }
  .fullScreenBox {
    position: fixed;
    bottom: 0;
    left: 20px;
    right: 20px;
    width: calc(100% - 40px);
  }
  .previewBox {
    height: 600px;
  }
}

::v-deep .el-tree {
  background: transparent;
  color: #ffffff;
}
::v-deep .el-tree-node__content:hover {
  background: linear-gradient(to right, #1b7ef2, #1b7ef200);
}
::v-deep .el-tree-node:focus > .el-tree-node__content {
  background: linear-gradient(to right, #1b7ef2, #1b7ef200);
}
::v-deep .el-carousel__container {
  height: 100%;
}
::v-deep .el-carousel__indicators {
  display: none;
}
/* 添加时间样式 */
.camera-time {
  position: absolute;
  right: 10px;
  bottom: 10px;
  color: #ffffff;
  font-size: 12px;
  background-color: transparent;
  padding: 2px 5px;
  border-radius: 3px;
}

.cameraItemBor {
  position: relative; /* 使时间定位生效 */
}
.video-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.loading-overlay,
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 18px;
}

.loading-text,
.error-text {
  padding: 10px 20px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
}
</style>
